package com.taxshare.manager.controller;

import cn.hutool.json.JSONObject;
import com.taxshare.manager.service.LoginService;
import com.taxshare.manager.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping(value = "/api/v1")
public class ApiController {

    @Autowired
    UserService userService;

    @Autowired
    LoginService loginService;


    @Value("${login.url}")
    private String loginUrl;

    /**
     * 获取token数据接口
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/getToken",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject getToken(@RequestBody(required = false) JSONObject jsonObject) {
        JSONObject result = new JSONObject();
        try{
            log.info("==========获取token数据接口 开始=====" + jsonObject);
            String appKey = jsonObject.getStr("appKey");
            String appSecret = jsonObject.getStr("appSecret");
            String token = getToken(appKey,appSecret);
            System.out.println("========token====>"+token);
            result.put("code", "0000");
            result.put("msg", "成功");
            result.put("token", token);
        }catch (Exception e){
            result.put("code", "9999");
            result.put("msg", e.getMessage());
            e.printStackTrace();
        }

        return result;
    }

    private String getToken(String appKey,String appSecret) {
        String signMy = "appKey=" + appKey;
        System.out.println(signMy);
        return sha256_HMAC(signMy, appSecret);
    }

    /**
     * 页面跳转
     * @param params
     * @return
     */
    @GetMapping("/toMenuUrl")
    public String toMenuUrl(@RequestParam Map<String, Object> params) throws Exception {
        log.info("=============页面跳转 toMenuUrl====开始========");
        String appKey = "7b43bb2b4ad34375a9fc4bcdf39b835e";
        String appSecret = "ndE2jdZNFixH9G6Aidsfyf7lYT3PxW";
        String username = String.valueOf(params.get("username"));
        String token_req = String.valueOf(params.get("token"));
        String redirectUrl = String.valueOf(params.get("redirectUrl"));
        String token_now = getToken(appKey,appSecret);
        String accessToken = "";
        String userNickName = "";
        String refreshToken = "";

        if(!token_now.equals(token_req)){
            accessToken = "token错误!";
            log.error(accessToken);
        }else{
            try {
                Map<String,Object> map = loginService.getToken01(username);
                String code = String.valueOf(map.get("code"));
                if(code.equals("0000")){
                    accessToken = String.valueOf(map.get("accessToken"));
                    userNickName = String.valueOf(map.get("userNickName"));
                    refreshToken = String.valueOf(map.get("refreshToken"));
                }else{
                    accessToken = String.valueOf(map.get("accessToken"));
                    log.error(accessToken);
                }
            }catch (Exception e){
                log.error("异常",e);
                e.printStackTrace();
            }
        }
        String url = loginUrl+"/#/login?accessToken="+accessToken
                +"&userNickName="+ URLEncoder.encode(userNickName,"UTF-8")+"&refreshToken="+refreshToken
                +"&thePath="+redirectUrl;
        log.info("=============页面跳转 toMenuUrl====结束========url=>"+url);
        return "redirect:"+url;
    }


    /**
     * sha256_HMAC加密
     *
     * @param message
     *            消息
     * @param secret
     *            秘钥
     * @return 加密后字符串
     */
    public static String sha256_HMAC(String message, String secret) {
        String hash = "";
        try {
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            byte[] bytes = sha256_HMAC.doFinal(message.getBytes("UTF-8"));
            hash = byteArrayToHexString(bytes);
        } catch (Exception e) {
            new Exception("Error HmacSHA256 加密异常:" + e.getMessage());
        }
        return hash;
    }

    /**
     * 将加密后的字节数组转换成字符串
     *
     * @param b
     *            字节数组
     * @return 字符串
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }
}
